import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * Creat by TanLei
 * Description:
 * User:86183
 * Date:2022-06-16
 * Time:13:51
 */
public class Test16 {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要遍历的目录：");
        String rootDirPath = scanner.next();
        System.out.println("请输入要查找的内容：");
        String content = scanner.next();

        File rootDir = new File(rootDirPath);
        if (!rootDir.isDirectory()) {
            System.out.println("输入的路径存在问题！");
            return;
        }
        List<File> results = new ArrayList<>();
        scanDirWithContent(rootDir, content, results);

        for (File f : results) {
            System.out.println(f.getCanonicalPath());
        }
    }

    private static void scanDirWithContent(File rootDir, String content, List<File> results) {
        File[] files = rootDir.listFiles();
        if(files == null){
            //空目录
            return;

        }
        for (File f : files) {
            if (f.isFile()) {
                if (isContentExists(f, content)) {
                    results.add(f);
                }
            } else if (f.isDirectory()) {
                scanDirWithContent(f, content, results);
            }
        }
    }
    private static boolean isContentExists(File f,String content){
        StringBuilder stringBuilder = new StringBuilder();
        try(Reader reader = new FileReader(f)){
            while(true){
                int c = reader.read();
                if(c==-1){
                    break;
                }
                stringBuilder.append((char) c);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return stringBuilder.indexOf(content)!=-1;
    }

}
